﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Sustainalytics.Admin.Synchronization.Utility;
using Sustainalytics.ESGRatings.BusinessLogic;

namespace Sustainalytics.CompanyReportSyncStep.CompanyReportOnline
{
    public class KEIPersistance
    {
        private ActionBlock<KEIData> _udpdaterBlock;
        private IKeyEsgIssuesRepository _repository;

        public KEIPersistance(IKeyEsgIssuesRepository repository)
        {
            Guard.ArgumentNotNull(repository, "repository");

            ExecutionDataflowBlockOptions options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 };

            Action<KEIData>  updateAction = UpdateKEIData;

            this._udpdaterBlock = new ActionBlock<KEIData>(updateAction, options);
            this._repository = repository;
        }

        private void UpdateKEIData(KEIData data)
        {
            if (data == null)
                return;
            _repository.UpdateIndicatorByCompanyIdAndIndicatorNumber(data.CompanyId,data.Data);           
        }

        public void Complete()
        {
            _udpdaterBlock.Complete();
        }

        public Task Completion
        {
            get
            {
                return _udpdaterBlock.Completion;
            }
        } 


        public void Push(Guid idCompany, List<KeyIndicatorData> data)
        {
            var keydata = new KEIData
            {
                CompanyId = idCompany,
                Data = data
            };
            _udpdaterBlock.Post(keydata);

        }

        private class KEIData
        {

            public Guid CompanyId { get; set; }


            public List<KeyIndicatorData> Data { get; set; } 
        }
    }


    
}
